package raochang.controller;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import raochang.pojo.entry.Books;
import raochang.pojo.entry.Reader;
import raochang.service.BooksService;
import raochang.service.ReadersService;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 图书数据 前端控制器
 * </p>
 *
 * @author itheima
 */
@RestController
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BooksService booksService;
    @Autowired
    private ReadersService readersService;
   private static final String sessionId = "YWYxNWFlOTctYjQ4MC00ZDM3LWExNDQtZmEzMDFkMjZiYmI1";
    /**
     * 导入图书数据入库-注意后里面访问url参数状态码
     */
    @GetMapping("/importBooks")
    public String importReads() {
        System.out.println("开始导入书籍...");
        for (int page = 1; page <= 663; page++) {
            try {
                booksService.importBooks(page, sessionId);
                System.out.println("导入成功到第:" + page + "页");
            } catch (Exception e) {
                System.out.println("在导入第 " + page + " 页时发生错误：" + e.getMessage());
                return "导入失败,在第:" + page + "页时发生错误";
            }
        }
        System.out.println("导入完成----");
        return "导入完成----";
    }

    /**
     * 借书  550
     */
    @GetMapping("/borrowBooks/{num}")
    public String borrowBooks(@PathVariable int num) {
        String url = "https://lib.scjyzb.cn/v1/circulation/returnBook";
        LocalDateTime localDateTime = LocalDateTime.now().minusDays(29);
        //借书之前先check下是否有延期没有还书数据
        List<Books> list = booksService.lambdaQuery()
                .eq(Books::getState, 1)//已经借出去的
                .le(Books::getSaveTime,localDateTime)
                .list();
        if (!CollectionUtils.isEmpty(list)) {
            System.out.println("查询到逾期书籍："+list.size()+"本");
            list.forEach(book -> {
                try {
                    sendReturnPOST(url, book.getBarcode(),sessionId);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                //改变数据库中书籍的状态
                booksService.lambdaUpdate().eq(Books::getBarcode, book.getBarcode())
                        .set(Books::getState, "0")
                        .set(Books::getReturnTime, LocalDateTime.now())
                        .update();
            });
        }else {
            System.out.println("未查询到逾期书籍");
        }
        //获取需要借书的班级数据
        //查询书读者借书数量排行前十的数据
        List<Reader> readers = readersService.lambdaQuery().list()
                .stream()
                .sorted(Comparator.comparing(Reader::getBorrowNum))
                .limit(10)
                .collect(Collectors.toList());
        booksService.borrowBooks(readers,sessionId,num);
        System.out.println("借书数据刷出完成***********");
        return "借书完成----";
    }


    /**
     * 还书  432
     */
    @GetMapping("/returnBooks/{num}")
    public String returnBooks(@PathVariable int num) {
        booksService.returnBooks(sessionId,num);
        return "还书完成----";
    }
    /**
     * 初始化借书信息
     */
    @GetMapping
    public String initBooks() {
        System.out.println("开始清洗数据----");
        for (int i = 1; i < 25; i++) {
            booksService.initBooks(i,sessionId);
            System.out.println("清洗第" + i + "页数据完成");
        }

        System.out.println("数据清洗完成--");
        return "初始化借书信息完成----";
    }

    private static final String USER_AGENT = "Mozilla/5.0";
    /**
     * 发送还书请求
     *
     * @param url
     * @param barcode
     * @throws Exception
     */

    private void sendReturnPOST(String url, String barcode,String sessionId) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("User-Agent", USER_AGENT);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Connection", "keep-alive");
//        httpPost.setHeader("Content-Length", "2");
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Cookie", "orgType=2; orgId=08534; SESSION="+sessionId+"; SF_cookie_11=78087231; menuUrl=/winshare-library/school/library/org_list");
        httpPost.setHeader("Host", "lib.scjyzb.cn");
        httpPost.setHeader("Origin", "https://lib.scjyzb.cn");
        httpPost.setHeader("Referer", "https://lib.scjyzb.cn/");
        httpPost.setHeader("sec-ch-ua", "\";Not A Brand\";v=\"99\", \"Chromium\";v=\"94\"");
        httpPost.setHeader("sec-ch-ua-mobile", "?0");
        httpPost.setHeader("sec-ch-ua-platform", "Windows");
        httpPost.setHeader("Sec-Fetch-Dest", "empty");
        httpPost.setHeader("Sec-Fetch-Mode", "cors");
        httpPost.setHeader("Sec-Fetch-Site", "same-origin");
        httpPost.setHeader("X-Requested-With", "XMLHttpRequest");
        String jsonPayload = "{\"barcode\": \"" + barcode + "\"}";
        HttpEntity entity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        httpResponse.getStatusLine().getStatusCode();
        System.out.println("已还数据code:" + barcode);
    }
}


